package com.example.quartz3.service;

import com.example.quartz3.job.Demo1Job;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class DemoService {

    @Autowired
    private Scheduler scheduler;//自动注入

    public String startJob(String name){
        Date date = new Date();
        JobDetail jobDetail = JobBuilder.newJob(Demo1Job.class).
                withIdentity("j"+date.toString(), "demo1")
                .usingJobData("name", name)
                .build();

        Date date1 = new Date(System.currentTimeMillis() + 5000);
        Trigger trigger1 = TriggerBuilder.newTrigger()
                .withIdentity("t" + date.toString(), "demo2")
//                .startAt(date1)//指定时间后执行
//                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).repeatForever())    ///每隔3秒执行一次
                .withSchedule(CronScheduleBuilder.cronSchedule("*/5 * * * * ?"))    //corn每隔5秒执行一次
                .build();
        try {
            scheduler.scheduleJob(jobDetail,trigger1);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
        return "success";

    }
}
